"""
配置文件 - 集中管理API认证token和其他配置信息
"""

# API认证配置
API_CONFIG = {
    # 通用access-token
    "access_token": "34b4be3b-bc91-483a-9516-e2a4710580cf_68f769cffddfaead455c5b78_client",
    # 可选的替代token (预留用于不同的token)
    "alternative_token": "",  # 留空，允许通过update_access_token函数更新
    # 默认使用的token键名
    "active_token": "access_token",  # 可以切换为 "alternative_token"
    
    # API基本配置
    "base_url": "https://app.abaka.ai",
    "api_version": "v2",
    
    # 默认请求超时时间（秒）
    "timeout": 60,
    
    # 默认用户代理
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
    
    # 默认语言设置
    "language": "zh-CN",
    "timezone": "Etc/GMT-8"
}

# 获取当前激活的token
def get_active_token():
    """
    获取当前激活的access-token
    
    Returns:
        str: 当前激活的access-token值
    """
    token_key = API_CONFIG["active_token"]
    # 优先获取指定的token
    token_value = API_CONFIG.get(token_key, "")
    
    # 如果指定的token为空，回退到access_token
    if not token_value or not token_value.strip():
        token_value = API_CONFIG.get("access_token", "")
        # 如果access_token也为空，设置一个默认的占位符
        if not token_value or not token_value.strip():
            token_value = ""
    
    return token_value

# 更新访问令牌
def update_access_token(token_value):
    """
    更新访问令牌的值
    
    Args:
        token_value (str): 新的访问令牌值
    
    Returns:
        bool: 更新是否成功
    """
    try:
        API_CONFIG["access_token"] = token_value
        # 确保使用更新后的token
        API_CONFIG["active_token"] = "access_token"
        return True
    except Exception as e:
        print(f"更新访问令牌失败: {str(e)}")
        return False

# 切换token
def switch_token(token_key="alternative_token"):
    """
    切换使用的token
    
    Args:
        token_key (str): token键名，"access_token" 或 "alternative_token"
    
    Returns:
        bool: 切换是否成功
    """
    if token_key in ["access_token", "alternative_token"]:
        # 检查要切换的token是否为空
        token_value = API_CONFIG.get(token_key, "")
        if not token_value or not token_value.strip():
            print(f"[警告] 无法切换到{token_key}，因为该token为空或无效")
            return False
        
        # 执行切换
        API_CONFIG["active_token"] = token_key
        # 安全地显示token信息
        display_token = f"{token_value[:10]}****{token_value[-4:]}" if token_value else "[空]"
        print(f"已切换到{token_key}，当前token: {display_token}")
        return True
    else:
        print(f"无效的token键名: {token_key}，必须是 'access_token' 或 'alternative_token'")
        return False

# 获取默认请求头
def get_default_headers(task_id=None, batch_id=None, item_id=None):
    """
    获取默认的API请求头
    
    Args:
        task_id (str, optional): 任务ID，用于构建Referer
        batch_id (str, optional): 批次ID，用于构建Referer
        item_id (str, optional): 项目ID，用于构建Referer
    
    Returns:
        dict: 默认的请求头字典
    """
    # 构建Referer
    if task_id and batch_id:
        referer = f"{API_CONFIG['base_url']}/task-v2/data-item?taskId={task_id}&vm=batch&batchId={batch_id}&dm=all"
    else:
        referer = f"{API_CONFIG['base_url']}/task-v2/data-item?taskId=68ef7506b89637431efa70dc&vm=batch&batchId=68f1e89b8fc939d1af1b726f&dm=all"
    
    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json",
        "language": API_CONFIG["language"],
        "origin": API_CONFIG["base_url"],
        "referer": referer,
        "sec-ch-ua": '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "trace-id": f"{get_random_trace_id()}",
        "user-agent": API_CONFIG["user_agent"],
        "x-timezone": API_CONFIG["timezone"],
        "access-token": get_active_token()
    }
    
    return headers

def get_random_trace_id():
    """
    生成随机的trace-id
    
    Returns:
        str: 随机的trace-id字符串
    """
    import uuid
    return str(uuid.uuid4())

# 打印当前配置信息
def print_config_info():
    """
    打印当前配置信息（不显示完整token）
    """
    token = get_active_token()
    masked_token = f"{token[:10]}****{token[-4:]}"
    
    print("===== API配置信息 =====")
    print(f"基础URL: {API_CONFIG['base_url']}")
    print(f"API版本: {API_CONFIG['api_version']}")
    print(f"活动token: {API_CONFIG['active_token']}")
    print(f"access-token: {masked_token}")
    print(f"超时时间: {API_CONFIG['timeout']}秒")
    print(f"默认语言: {API_CONFIG['language']}")
    print(f"时区设置: {API_CONFIG['timezone']}")
    print("======================")